#!/bin/bash

# TCP2MQTT 网关图形界面启动脚本
# Linux 平台专用

echo "======================================="
echo "       TCP2MQTT 网关图形界面启动器"
echo "======================================="

# 设置工作目录为脚本所在目录
cd "$(dirname "$0")"

echo "工作目录: $(pwd)"

# 检查Python是否安装
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到Python。请先安装Python 3.6或更高版本。"
    read -p "按回车键继续..."
    exit 1
fi

# 使用python3命令
PYTHON_CMD=python3

# 检查虚拟环境是否存在
if [ ! -d "venv" ]; then
    echo "未找到虚拟环境，正在创建..."
    $PYTHON_CMD -m venv venv
    
    # 激活虚拟环境
    source venv/bin/activate
    
    # 升级pip
    echo "正在升级pip..."
    pip install --upgrade pip
    
    # 安装依赖
    echo "正在安装依赖包..."
    pip install -r requirements.txt
    
    # 检查安装是否成功
    if [ $? -ne 0 ]; then
        echo "错误: 依赖安装失败。"
        read -p "按回车键继续..."
        exit 1
    fi
    
    echo "依赖安装完成。"
else
    # 激活已存在的虚拟环境
    source venv/bin/activate
    
    # 检查是否需要更新依赖
    echo "检查依赖更新..."
    pip install -r requirements.txt --upgrade
fi

# 检查Tkinter是否可用
echo "检查Tkinter可用性..."
$PYTHON_CMD -c "import tkinter; print('Tkinter可用')" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "警告: 未找到Tkinter。请安装python3-tk包。"
    echo "在Debian/Ubuntu上: sudo apt-get install python3-tk"
    echo "在CentOS/RHEL上: sudo yum install python3-tkinter"
    read -p "是否继续? (y/n): " choice
    if [ "$choice" != "y" ] && [ "$choice" != "Y" ]; then
        exit 1
    fi
fi

# 启动图形界面
echo "启动TCP2MQTT网关图形界面..."
$PYTHON_CMD tcp2mqtt_gui.py

# 检查启动是否成功
if [ $? -ne 0 ]; then
    echo "错误: 图形界面启动失败。"
    read -p "按回车键继续..."
    exit 1
fi

# 程序退出
echo "程序已退出。"
read -p "按回车键继续..."